package reflect;
//暴力反射对String的破坏

import java.lang.reflect.Field;
import java.util.Arrays;

public class ReflectDemo10 {
    public static void main(String[] args) throws Exception {
        String s1 = "123abc";
        String s2 = "123abc";
        System.out.println("s1:" + s1);
        System.out.println("s2:" + s2);

        /* 获取String类 */
        Class cls = String.class;
        /* 获取String类的私有字段value，它存储了字符串的实际字符数组 */
        Field field = cls.getDeclaredField("value");
        /* 设置field为可访问，以绕过Java的访问控制 */
        field.setAccessible(true);

        /* 从字符串s1中获取字符数组value */
        char[] value = (char[]) field.get(s1);
        System.out.println(Arrays.toString(value));
        /* 修改字符数组value的值 */
        value = new char[]{'h', 'e', 'l', 'l', 'o'};
        /* 将修改后的字符数组赋值回s1的value字段 */
        field.set(s1, value);
        System.out.println("s1:" + s1);
        System.out.println("s2:" + s2);

        String s3 = "123abc";
        System.out.println("s3:" + s3);

    }
}
